/**
 * 
 */
package com.pkche.core.advanced.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * Describe：提供IPv4地址字符串与10进制互相转换的方法<br />
 * User："Qiang" <br/>
 * Time：2015年2月15日 上午11:44:43 <br/>
 */
public class IpAddressTransition {
	/**
	 * 将数字型ipv4地址转换成字符串
	 * 
	 * @param ip_number
	 * @return
	 */
	public static String convertIpv4(long ip_number) {
		String str = "";
		long temp = 0;
		for (int i = 3; i >= 0; i--) {
			temp = ip_number / (long) Math.pow(256, i) % 256;
			if (i == 3) {
				str = str + temp;
			} else {
				str = str + "." + temp;
			}
		}
		return str;
	}

	/**
	 * 将ipv4地址字符串转换成10进制
	 * 
	 * @param ip
	 * @return
	 */
	public static long convertIpv4(String ip) {
		long number = 0l;
		if("unknown".equals(ip)){
			number = 0l;
			return number;
		}
		String[] array = ip.trim().split("\\.");
		for (int i = 0; i < 4; i++) {
			number += Math.pow(256, 3 - i) * Integer.parseInt(array[i]);
		}
		return number;
	}
	
	/**
	 * 获取真实的ip地址，可能存在前端代理
	 * 
	 * @return
	 */
	public static String getRemoteAddr(HttpServletRequest request) {
		String from_nginx_ip = request.getHeader("X-Forwarded-For");
		if ((from_nginx_ip == null) || (from_nginx_ip.length() == 0)) {
			return request.getRemoteAddr();
		} else {
			return from_nginx_ip;
		}
	}
	
	/**
	 * 验证IP地址字符串是否为合法的IPv4地址
	 * 
	 * @param ip
	 * @return
	 */
	public final static boolean isIPv4InetAddress(String ip) {
		InetAddress inet_addr = null;
		try {
			// 验证地址有效性
			inet_addr = InetAddress.getByName(ip);
		} catch (UnknownHostException e) {
			return false;
		}
		// 检查地址是否为ipv4地址
		if (inet_addr instanceof Inet4Address) {
			return true;
		}
		return false;
	}

}
